SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO


CREATE PROCEDURE dbo.[DnnProduct_CalculatePagingInformation]
(
	@pageIndex int, 
	@pageSize int, 
	@rowsToReturn int = null output, 
	@pageLowerBound int = null output, 
	@pageUpperBound int = null output
)
as
	begin

		declare 
			@minValue int, 
			@maxValue int, 
			@maxPageIndex int, 
			@pageSizeBig bigint, 
			@pageIndexBig bigint, 
			@rowsToReturnBig bigint, 
			@pageLowerBoundBig bigint, 
			@pageUpperBoundBig bigint

		select
			@minValue = 0, 
			@maxValue = cast(0x7fffffff as int), 
			@maxPageIndex = @maxValue / @pageSize, 
			@pageSizeBig = @pageSize, 
			@pageIndexBig = @pageIndex

		if (@pageSize = 0 and @pageIndex = 0) 
				or @pageSize = @maxValue
				or @pageIndex < 0 
				or @pageSize < 0 
				or @pageSize is null
				or @pageIndex is null
			begin
				select
					@rowsToReturn = @maxValue, 
					@pageLowerBound = 0, 
					@pageUpperBound = @maxValue
			end 
		else 
			begin
				select
					@rowsToReturnBig = @pageSizeBig * (@pageIndexBig + 1), 
					@pageLowerBoundBig = @pageSizeBig * @pageIndexBig, 
					@pageUpperBoundBig = @pageLowerBoundBig + @pageSizeBig + 1
 
				select
					@rowsToReturn = case when @rowsToReturnBig <= @maxValue then cast(@rowsToReturnBig as int) else @maxValue end, 
					@pageLowerBound = case when @pageLowerBoundBig <= @maxValue then cast(@pageLowerBoundBig as int) else @maxValue end, 
					@pageUpperBound = case when @pageUpperBoundBig <= @maxValue then cast(@pageUpperBoundBig as int) else @maxValue end
			end
	end
GO
